#include "stdafx.h"
#include "render/font.h"
#include "render/render.h"
#include <allegro5/allegro.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>

#ifdef DrawText
#undef DrawText
#endif

namespace Render
{

inline ALLEGRO_COLOR AllegroColour(uint32 rgba)
{
	float a = (rgba & 0xff) / 255.f;
	float r = (rgba >> 24) * a / 255.f;
	float g = ((rgba >> 16) & 0xff) * a / 255.f;
	float b = ((rgba >> 8) & 0xff) * a / 255.f;
	return al_map_rgba_f(r, g, b, a);
}

inline ALLEGRO_BITMAP* AllegroBitmap(SurfacePtr pSurface)
{
	return (ALLEGRO_BITMAP*) pSurface;
}

Font* LoadFont(const char* filename, int size)
{
	ALLEGRO_FONT *pFont = al_load_ttf_font(filename, size, 0);
	return (Font*) pFont;
}

void FreeFont(Font* pFont)
{
	al_destroy_font((ALLEGRO_FONT*) pFont);
}

void DrawText(int x, int y, const Font* pFont, const char* pText, uint32 rgba)
{
	al_draw_text((ALLEGRO_FONT*) pFont, AllegroColour(rgba), x, y, ALLEGRO_ALIGN_INTEGER, pText);
}

Render::Surface DrawToNewSurface(const Font* pFont, const char* pText, uint32 rgba)
{
	int w = al_get_text_width((ALLEGRO_FONT*) pFont, pText);
	int a = al_get_font_ascent((ALLEGRO_FONT*) pFont);
	int d = al_get_font_descent((ALLEGRO_FONT*) pFont);

	Surface pSurface = CreateSurface(w + 1, a + d);

	ALLEGRO_BITMAP* pOriginalTarget = al_get_target_bitmap();
	al_set_target_bitmap(AllegroBitmap(pSurface));
	al_draw_text((ALLEGRO_FONT*) pFont, AllegroColour(rgba), 0, 0, ALLEGRO_ALIGN_INTEGER, pText);
	al_set_target_bitmap(pOriginalTarget);

	return pSurface;
}

int GetWidth(const Font* pFont, const char* pText)
{
	return al_get_text_width((ALLEGRO_FONT*) pFont, pText);
}

int GetHeight(const Font* pFont, const char* pText)
{
	return al_get_font_ascent((ALLEGRO_FONT*) pFont) + al_get_font_descent((ALLEGRO_FONT*) pFont);
}

}
